//https://leetcode.cn/problems/combination-sum/submissions/562871702/
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;
    int sum;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        dfs(candidates, target, 0);
        return ret;
    }
    public void dfs(int[] candidates, int target, int pos) {
        if(sum >= target || pos >= candidates.length) {
            if(sum == target) ret.add(new ArrayList<>(path));
            return;
        }
        for(int k = 0; candidates[pos] * k <= target; k++) {
            if(k != 0) { 
            path.add(candidates[pos]);
            sum += candidates[pos];
            }
            dfs(candidates, target, pos + 1);
        }
        //回溯 -> 恢复现场
        for(int k = 1; candidates[pos] * k <= target; k++) {
            sum -= candidates[pos];
            path.remove(path.size() - 1);
        }
    }
}